package com.sghj.utils;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;

public class ImageProcess {
//    //将图片压缩并转为64编码
    public String minimiseImage(String path, String filename) throws IOException {


        //获取图片大小
        File targetFile=new File(path+"//"+filename);
        String abpath=targetFile.getAbsolutePath();
        String lpath=abpath.substring(0,abpath.lastIndexOf("\\")+1);

        String oldfi=path+"\\"+filename;
        String picsize=String.format("%.1f", targetFile.length() / 1024.0);
        while (Float.valueOf(picsize).floatValue() > 20) {
            String newfi = path + "\\" + filename.substring(0, filename.indexOf(".")) +
                    "压缩版" + filename.substring(filename.indexOf("."));
            Thumbnails.of(oldfi)
                    .scale(0.8f)
                    .outputQuality(1f)
                    .toFile(newfi);
            targetFile = new File(newfi);
            picsize = String.format("%.1f", targetFile.length() / 1024.0);
            oldfi = newfi;
        }
       // System.out.println("oldfi"+oldfi);
        String refi=oldfi.substring(oldfi.lastIndexOf("\\")+1);
       // System.out.println("名"+refi);

        String base64= "data:image/bmp;base64,"+Base64Encoder.encode(FileUtil.readBytes(lpath+refi));

        if(refi.contains("压缩版")) {
            File ff = new File(lpath + refi);
            ff.delete();
        }
        return base64;

    }

}
